package com.hd.trans.network.factory

import android.util.Log
import com.google.gson.Gson
import com.hd.trans.TranslationInterior
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.JsonReader
import okhttp3.ResponseBody
import okio.ByteString.Companion.decodeHex
import retrofit2.Converter
import java.lang.reflect.Type


class CustomResponseBodyConverter<T>(val adapter: JsonAdapter<T>,val type: Type) : Converter<ResponseBody, T> {

    private val UTF8_BOM = "EFBBBF".decodeHex()

    override fun convert(value: ResponseBody): T? {

        //如果type是String类型
        if(type == String::class.java){
            val string = value.string()
            log(string)
            return string as T
        }

        //如果type是SseStreamText类型
        if(type == SseStreamText::class.java){
            val string = value.string()
            log(string)
            return SseStreamText.parse(string) as T
        }

        return try {
            val source = value.source()
            // Moshi has no document-level API so the responsibility of BOM skipping falls to whatever
            // is delegating to it. Since it's a UTF-8-only library as well we only honor the UTF-8 BOM.
            if (source.rangeEquals(0, UTF8_BOM)) {
                source.skip(UTF8_BOM.size.toLong())
            }
            val reader = JsonReader.of(source)
            val result = adapter.fromJson(reader)
            if (reader.peek() != JsonReader.Token.END_DOCUMENT) {
                throw JsonDataException("JSON document was not fully consumed.")
            }

            log(result)

            result
        } finally {
            value.close()
        }
    }

    private fun log(any: Any?){
        if (TranslationInterior.isDebug()) {
            val string:String = when{
                any == null -> "null"
                any is String -> any
                else -> Gson().toJson(any)
            }
            Log.i("okhttp.OkHttpClient", "CustomResponseBodyConverter#convert() called with: value = $string")
        }
    }


}